<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:sq="http://www.w3.org/1999/html">
<head>
  <th:block th:include="include :: header" />
  <link th:href="@{/assets/css/plugins/chosen/chosen.css}" rel="stylesheet">
</head>

<body class="gray-bg">
<div class="wrapper wrapper-content">
  <div class="row">
    <div class="col-sm-3">
      <div class="ibox float-e-margins">
        <div class="ibox-content mailbox-content">
          <div class="file-manager">
            <a class="btn btn-block btn-primary compose-mail" href="#" onclick="addOrg()">新增机构</a>
            <div class="space-25"></div>
            <ul id="tree" class="ztree" style="width:auto; overflow:auto;"></ul>
            <div class="clearfix"></div>
          </div>
        </div>
      </div>
    </div>
    <div class="col-sm-9 animated fadeInRight">
      <div class="ibox float-e-margins">
        <div class="ibox-title">
          <h5>编辑</h5>
          <div class="ibox-tools">
            <a class="collapse-link">
              <i class="fa fa-chevron-up"></i>
            </a>
          </div>
        </div>
        <div class="ibox-content">
          <form class="form-horizontal m-t" id="editFrom">
            <div class="form-group">
              <label class="col-sm-3 control-label">上级机构:</label>
              <div class="col-sm-8">
                <input type="hidden" id="parentId" name="parentId" value="0" class="form-control">
                <input type="text" id="parentName" name="parentName" value="根机构" class="form-control"
                       disabled="disabled">
              </div>
            </div>
            <div class="form-group">
              <label class="col-sm-3 control-label">机构名称:</label>
              <div class="col-sm-8">
                <input type="hidden" id="id" name="id">
                <input id="name" name="name" type="text" class="form-control" required="" aria-required="true">
              </div>
            </div>
            <div class="form-group">
              <label class="col-sm-3 control-label">备注:</label>
              <div class="col-sm-8">
                <textarea id="remark" name="remark" maxlength="200" class="form-control"></textarea>
              </div>
            </div>
            <div class="form-group">
              <div class="col-sm-4 col-sm-offset-3" id="b">
                <button class="btn btn-primary" type="button" onclick="saveData()">提交</button>
                <button class="btn btn-danger" type="button" onclick="del()">删除</button>
              </div>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</div>
</body>
<th:block th:include="include :: footer" />
<script th:src="@{/assets/js/plugins/chosen/chosen.jquery.js}"></script>
<script th:inline="javascript">
    const requestPath = parent.api.sys.org
    $(function () {
        //屏蔽删除按钮
        $(".btn-danger").hide();

        //初始化树
        initTree();

        //表单提交路径
        $("#editFrom").attr("action", requestPath.save)

        //初始化复选框样式
        $(".i-checks").iCheck({
            checkboxClass: "icheckbox_square-green",
            radioClass: "iradio_square-green"
        })

        //初始化多选下拉框数据
        initChosenDate();

        //初始化多选下拉框控件
        var config = {
            ".chosen-select": {},
            ".chosen-select-deselect": {allow_single_deselect: false},
            ".chosen-select-no-single": {disable_search_threshold: 10},
            ".chosen-select-no-results": {no_results_text: "Oops, nothing found!"},
            ".chosen-select-width": {width: "95%"}
        };
        for (var selector in config) {
            $(selector).chosen(config[selector]);
        }
    });

    //初始化树结构
    function initTree() {
        var setting = {
            check: {
                enable: false,
                chkStyle: "radio",
                radioType: "all"
            },
            view: {
                dblClickExpand: false,
                showLine: true,
                selectedMulti: false
            },
            data: {
                simpleData: {
                    enable: true,
                    idKey: "id",
                    pIdKey: "parentId",
                    rootPId: ""
                }
            },
            callback: {
                onClick: zTreeOnClick
            }
        };

        $.fn.zTree.init($("#tree"), setting, [[${treeList}]]);
    }

    //获取点击菜单信息
    function zTreeOnClick(event, treeId, treeNode) {
        $.ajax({
            type: "get",
            url: requestPath.index+'/'+treeNode.id,
            data: '',
            dataType: "json",
            success: function (data) {
                if (data && data.success === true) {
                    loadData(data.info.org, treeNode.getParentNode())
                    loadStation(data.info.stations);
                } else {
                    //TODO 弹出错误信息
                }
            }
        });
    }

    //加载机构数据
    function loadData(data, pNode) {
        $("#id").val(data.id);
        $("#name").val(data.name);
        $("#parentId").val(data.parentId);
        $("#remark").val(data.remark);
        $(".btn-danger").show();//显示删除按钮
        if (data.parentId == "0") {
            $("#parentName").val("根机构");
        } else {
            if (pNode != null) {
                $("#parentName").val(pNode.name);
            } else {
                $("#parentName").val("");
            }
        }
    }

    //加载管辖场站多选框信息
    function loadStation(stationList) {
        //判断是否有该场站
        if (stationList != null && stationList != "undefined") {
            //重新初始化下拉框数据
            initChosenDate();
            //设置下拉框选中数据
            for (var s = 0; s < stationList.length; s++) {
                $("#station option[value=" + stationList[s].id + "]").attr("selected", "selected");
            }
        } else {
            $("#station").val("");
        }
        $("#station").trigger("chosen:updated");
        $("#station").chosen();
    }

    //初始化多选下拉框数据
    function initChosenDate() {
        //初始化多选下拉框下拉数据
        $("#station option").remove();
        [[${allStations}]].forEach(function(item) {
            $("#station").append('<option value= '+item.idStr+'> '+item.staName+' </option>');
        })
    }

    //新增机构
    function addOrg() {
        var treeObj = $.fn.zTree.getZTreeObj("tree");
        var nodes = treeObj.getSelectedNodes();
        $('#editFrom')[0].reset();
        $("#id").val("");
        $(".btn-danger").hide();
        $("#parentId").val(nodes[0] ? nodes[0].id : 0);
        $("#parentName").val(nodes[0] ? nodes[0].name : "根机构");
        $("#station").val("");
        $("#station").trigger("chosen:updated");
        //屏蔽删除按钮
        $(".btn-danger").hide();
    }

    //保存
    function saveData() {
        let data = {}
        if ($("#station").val()) {
            data.stationIds = $("#station").val().join(',')
        }
        $("#editFrom").serializeArray().forEach(function(item) {
            if (item.value) {
                data[item.name] = item.value
            }
        })
        if ($("#editFrom").valid()) {
            $.ajax({
                type: "post",
                url: requestPath.save,
                data: data,
                dataType: "json",
                success: function (data) {
                    if (data.success == true) {
                        swal("保存成功!");
                        setTimeout(function () {
                            $("#editFrom")[0].reset();
                            window.location.reload();
                        }, 1000);
                    } else {
                        swal("保存失败!");
                    }
                }
            })
        }
    }

    //删除
    function del() {
        swal({
                title: "您确定要删除这条信息吗",
                text: "删除后将无法恢复，请谨慎操作！",
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "删除",
                closeOnConfirm: false
            },
            function () {
                $.ajax({
                    type: "get",
                    url: requestPath.del,
                    data: "id=" + $("#id").val(),
                    dataType: "json",
                    success: function (data) {
                        if (data.success == true) {
                            swal("删除成功!");
                            setTimeout(function () {
                                $("#editFrom")[0].reset();
                                window.location.reload();
                            }, 1000)
                        }
                    }
                })
            }
        )
    }
</script>
</html>